<template lang="html">
  <div>
    <div class="btn">
        <el-button type="primary" @click="back">返回上一级</el-button>
        <el-button type="primary" @click="add">新增分组</el-button>
        <el-button type="primary" @click="addVal">新增选项（属性）</el-button>
        <el-button type="primary" @click="compile">编辑选项（属性）</el-button>
    </div>
    <div class="add">
       <p><label>科目名称：</label><span>{{JSON.parse(this.$route.query.item).subjectName}}</span></p>
       <p><label>质检类目：</label><el-select v-model="pageData.qualifyCategoryId" placeholder="请选择" disabled>
               <el-option
                 v-for="item in isVal"
                 :key="item.qualifyCategoryId"
                 :label="item.categoryName"
                 :value="item.qualifyCategoryId">
               </el-option>
              </el-select></p>
    </div>
    <tableVue :list="list" :state="false" v-loading="pageData.loading" :pagination="true" :radioShwo="true" @changeData="getRow">
      <slot>
        <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEdit(scope.row,1)">编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                class="del"
                @click="del(scope.row,2)">删除</el-button>
            </template>
        </el-table-column>
      </slot>
    </tableVue>
    <dialogVue title="操作" :dialog="dialog" @close="changeData" :state="false">
        <slot>
              <el-form :model="pageData" :rules="rules" ref="ruleForm" label-width="200px" class="demo-ruleForm">
                  <el-form-item label="组名称" prop="groupName">
                      <el-input v-model="pageData.groupName" placeholder="请输入内容"></el-input>
                   </el-form-item>
                   <el-form-item label="是否必须检测" prop="isNeed">
                     <el-select v-model="pageData.isNeed" placeholder="请选择">
                       <el-option
                         v-for="item in need"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                       </el-option>
                      </el-select>
                    </el-form-item>
                   <el-form-item label="描述">
                       <el-input v-model="pageData.groupDesc" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input v-model="pageData.orindal" placeholder="请输入内容"></el-input>
                     </el-form-item>
                    <el-form-item class="confirm">
                       <el-button type="primary" v-if="btnState == '1'" @click="upForm('post')">提交</el-button>
                       <el-button type="primary" v-if="btnState == '2'" @click="upForm('put')">更新</el-button>
                    </el-form-item>
              </el-form>
        </slot>
    </dialogVue>
    <el-dialog
      title="提示"
      :visible.sync="valdialog"
      width="90%">
      <!-- <tableVue
        ref="upTable"
        :list="optionlist"
        :state="true"
        v-loading="loading"
        :total="total"
        @sizeChange="handSize"
        @changeData="choice">
      </tableVue> -->

      <el-table
        ref="editTable"
        :data="optionlist.tbody"
        tooltip-effect="dark"
        style="width: 100%"
        @select-all="handleSelectionChange"
        @select="handleSelectionChange">
        <!-- @selection-change="handleSelectionChange" -->
        <el-table-column
          type="selection"
          width="80">
        </el-table-column>

        <el-table-column
          v-for='(item,idx) in optionlist.thead' :label="item.label"  :key='idx' align="center">
          <template slot-scope="scope">{{ scope.row[item.prop] }}</template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleSizeChange"
        :page-sizes="[10]"
        :page-size="15"
         layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>






      <div class="fot">
        <el-button @click="valdialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmoption('post')">确 定</el-button>
      </div>
      <!-- <span slot="footer" class="dialog-footer">

      </span> -->
    </el-dialog>
  </div>
</template>

<script>
  import dialogVue from '@/components/dialog.vue'
  import tableVue from '@/components/alltable.vue'
  import {
    groupingList,
    addgrouping,
    addoption,
    delgrouping,
    optionList,
    qualityClassList
  } from "@/api/shoppingCentre/shoppingCentre";
  export default {
    components : {
      tableVue,
      dialogVue
    },
    data () {
      return {
          dialog : false,
          valdialog : false,
          total :0,
          btnState : '',
          need : [{value : 'Y',label : '是'},{value : 'N',label : '否'}],
          loading : false,
          pageData : {
            loading : true,
            isNeed : 'N',
            groupDesc : '',
            orindal :'1',
            qualifyCategoryId : '',
          },
          optionData : {
              attrList : []
          },
          attrList :[],
          getList :{},
          list : {
            thead : [
              {label:'排序',prop:"orindal",rowspan:1},
              {label:'分组名称',prop:"groupName",rowspan:1},
              {label:'描述',prop:"groupDesc",rowspan:1},
              {label:'创建时间',prop:"gmtCreate",rowspan:1},
              {label:'更新时间',prop:"gmtUpdate",rowspan:1},
            ],
            tbody : []
          },
          optionlist : {
            thead : [
              {label:'检测属性名称',prop:"attrName",rowspan:1},
              {label:'是否必须检测属性',prop:"isNeed",rowspan:1},
            ],
            tbody : []
          },
          isVal: [],
          rules : {
            groupName: [ { required: true, message: '请输入内容', trigger: 'blur' }],
            isNeed: [ { required: true, message: '请输入内容', trigger: 'change' }]
          },
          currentPageNum:1,
      }
    },
    mounted () {
      var data = {
        subjectId	 : JSON.parse(this.$route.query.item).subjectId
      }
      this.getgroupingListList(data);
      this.getqualityClassList();
      this.pageData.qualifyCategoryId  = JSON.parse(this.$route.query.item).qualifyCategoryId

    },
    methods : {
      getqualityClassList () {//拉取所有的类目
        qualityClassList().then(res=>{
          if (res.data.code == 'OK') {
             this.isVal = res.data.data.records;
          }
        })
      },
      getgroupingListList (data) {
        groupingList(data).then(res=>{
          if (res.data.code == 'OK') {
            console.log(res)
            this.pageData.loading = false;
            this.list.tbody = res.data.data.map(item=>{
               item.gmtCreate = this.switchTime(item.gmtCreate)
               item.gmtUpdate = this.switchTime(item.gmtUpdate)
               return item;
            });
          } else {
             setTimeout(()=>{
               this.pageData.loading = false;
             },2000)
          }
        })
      },
      back () {
        this.$router.push({
          name : 'qualityCourse'
        })
      },
      changeData (data) {
          this.dialog = data;
      },
      getRow (val) {
        this.getList = val;
        console.log(val)
      },
      handleSelectionChange (val) {
        this.optionlist.tbody.map(item=>{
          console.log(this.attrList);
          if(this.attrList.indexOf(item.attrId) != -1){
            this.attrList.splice(this.attrList.indexOf(item.attrId),1);
          }
        });
        val.map(item=>{
          if(this.attrList.indexOf(item.attrId) == -1){
            this.attrList.push(item.attrId)
          }
        });
      },
      handleSizeChange (val) {
        this.currentPageNum = val;
        var data = {
          current :val,
          size : '5'
        }
        this.getoptionList(data);
      },
      add () {
        this.pageData = {};
        this.dialog = true;
        this.btnState = '1';
        this.$refs.ruleForm&&this.$refs.ruleForm.resetFields()
      },
      addVal () {
        this.attrList = [];
        if (JSON.stringify(this.getList) == "{}") {
              this.$message.error('请选择要添加分组的属性');
        } else {
           this.valdialog = true
           var data = {
             current : '1',
             size : '5'
           }
           this.getoptionList(data);
        }
      },
      compile () {
        if (JSON.stringify(this.getList) == "{}") {
            this.$message.error('请选择编辑的组');
            return
        }
        this.attrList =[];
        if(this.getList.attrList && this.getList.attrList.length>0){
          this.getList.attrList.map(item=>{
            this.attrList.push(item.attrId);
          })
        }
          this.valdialog = true
          var data = {
            current : '1',
            size : '5'
          }
          this.getoptionList(data);

      },
      confirmoption (method) {
        if (this.attrList.length < 1) {
            this.$message.error('请选择添加属性');
        } else {
          var data = {
            groupId : this.getList.groupId,
            attrList : this.attrList,
          }
          addoption(data,method).then(res=>{
            if (res.data.code == 'OK') {
                 this.$message.success('操作成功');
                 this.$router.push({
                   name : 'qualityCourse'
                 })
            } else {
              this.$message.error(res.data.messages);
            }
          })
        }
      },
      getoptionList (data) {
        optionList(data).then(res=>{
          this.loading = true;
          if (res.data.code == 'OK') {
            this.loading = false;
            this.total = res.data.data.total;
            this.optionlist.tbody = res.data.data.records.map(item=>{
               item.gmtCreate = this.switchTime(item.gmtCreate)
               item.gmtUpdate = this.switchTime(item.gmtUpdate)
               item.isNeed = item.isNeed == 'Y' ? '是' : '否'
               return item;
            });
            var t = setTimeout(() => {
              this.attrList.forEach(item => {

                  let select_row = this.optionlist.tbody.find(t=>t.attrId == item);
                  if(select_row){
                    this.$refs.editTable.toggleRowSelection(select_row, true);
                  }
              });
              clearTimeout(t);
            }, 0);
          } else {
             setTimeout(()=>{
               this.loading = false;
             },2000)
          }
        })
      },
      handleEdit (item) {
        this.$refs.ruleForm&&this.$refs.ruleForm.resetFields();
        this.btnState = '2';
        this.dialog = true;
        this.pageData.groupName = item.groupName;
        this.pageData.isNeed = item.isNeed;
        this.pageData.groupId = item.groupId;
        this.pageData.groupDesc = item.groupDesc;
      },
      upForm (method) {
        this.$refs.ruleForm.validate((valid)=>{
           if (valid) {
             var data = {
               subjectId : JSON.parse(this.$route.query.item).subjectId,
               groupName : this.pageData.groupName,
               isNeed : this.pageData.isNeed,
               orindal : this.pageData.orindal,
               groupDesc : this.pageData.groupDesc,
               groupId : this.pageData.groupId
             }
             addgrouping(data,method).then(res=>{
               if (res.data.code == 'OK') {
                   this.dialog = false;
                   var data = {
                     subjectId : JSON.parse(this.$route.query.item).subjectId
                   }
                   this.getgroupingListList(data);
                   if (method == 'post') {
                       this.$message.success('新增成功');
                   } else {
                      this.$message.success('编辑成功');
                   }
                } else {
                  this.$message.error(res.data.messages);
                }
             })
           }
        })
      },
      del (item) {
        this.delMessage(()=>{
          var id = [];
          id.push(item.groupId)
          delgrouping(id).then(res=>{
            if (res.data.code == 'OK') {
              var data = {
                subjectId	 : JSON.parse(this.$route.query.item).subjectId
              }
              this.getgroupingListList(data);
              this.$message.success('删除成功');
            } else {
              this.$message.error(res.data.message);
            }
          })
        })
      },
    }
  }
</script>

<style scoped>

  @import "../../../../../styles/common.css";
  .btn {
    margin-top: 10px;
  }
  .add {
    background-color: #fff;
    padding: 20px;
  }
  .el-dialog__footer {
    padding: 48px 28px 20px !important;
  }
  .fot {
    margin-top: 82px;
    display: flex;
    justify-content: flex-end;
    margin-right: 20px;
  }
</style>
